package cn.ainit.sys.pagescript;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import org.hibernate.Query;
import org.junit.Test;
import org.springframework.stereotype.Repository;

import cn.ainit.sys.common.dao.BusinessBaseDao;
import cn.ainit.sys.pages.config.entity.ConfigObject;
import cn.ainit.sys.pagescript.entity.ButtonObject;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.ui.forms.Columns;

@Repository
public class PageCommonDaoImpl extends BusinessBaseDao implements PageCommonDao{

	
	@Override
	public ButtonObject findButObjectById(String butId) throws Exception {
		String hql = "from ButtonObject bo where bo.butId = ?";
		Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
		query.setString(0, butId);
		List<ButtonObject> buttonObjects = query.list();
		if (buttonObjects != null && buttonObjects.size() > 0) {
			return buttonObjects.get(0);
		}
		return null;
	}
	
	@Override
	public String executeSql(String sqlTxt, String[] sqlParamStr)
			throws Exception {
		String info = "false";
		PreparedStatement pstmt = this.getJdbcTemplate().getDataSource().getConnection().prepareStatement(sqlTxt);
		try {
			for (int i = 1; i <= sqlParamStr.length; i++) {
				pstmt.setString(i, sqlParamStr[i-1]);
			}
			pstmt.execute();
			info = "true";
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return info;
	}
	
	@Override
	public String[] executeProc(String procTxt, String[] procParamStr)
			throws Exception {
		String[] returnMsg = {};
		Connection conn=null;
		CallableStatement cstmt=null;
		try {
			//转换存储过程
			String callP = procTxt.split("\\(")[0];
			String[] callName = procTxt.split(",");
			StringBuffer orclProcName = new StringBuffer("");
			if (callName.length != procParamStr.length) {
				throw new RuntimeException("存储过程参数个数不匹配");
			}else{
				orclProcName = new StringBuffer("{call "+callP+"(");
				for (int i = 0; i < procParamStr.length; i++) {
					orclProcName.append("?");
					if (i != procParamStr.length - 1) {
						orclProcName.append(",");
					}
				}
				orclProcName.append(")}");
			}
			//检测输出参数
			String[] ps = procTxt.split(",");
			ps[0] = ps[0].split("\\(")[1];
			String outP = "";
			for (int i = 0; i < ps.length; i++) {
				if (ps[i].trim().matches("\\w+\\sout\\s.+")) {
					outP += ","+String.valueOf(i)+"|";
				}
			}
			System.out.println(orclProcName.toString()+"=========");
			conn=this.getJdbcTemplate().getDataSource().getConnection();
			
			//存储过程
			cstmt = conn.prepareCall(orclProcName.toString());//"{call pro2(?,?)}"
			//设置参数
			for (int i = 0; i < procParamStr.length; i++){
				if (outP.indexOf(","+String.valueOf(i)+"|") >= 0) {
					cstmt.registerOutParameter(i+1, java.sql.Types.VARCHAR);
					System.out.println("注册返回参数   "+i+1);
				}else {
					cstmt.setString(i+1, procParamStr[i]);
					System.out.println("传入参数    "+ procParamStr[i]);
				}
			}
//			cstmt.setInt(1, 35);
//			cstmt.setString(2, "zzzzzzzzz");
//			cstmt.registerOutParameter(3, java.sql.Types.var)
			cstmt.execute();
			String[] rsr = outP.split("\\|");
			for (int i = 0; i < rsr.length; i++) {
				returnMsg[i] = cstmt.getString(Integer.parseInt(rsr[i].substring(1, rsr[i].length())));
				System.out.println(returnMsg[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if(cstmt!=null){
				cstmt.close();
			}
			if(conn!=null){
				cstmt.close();
			}
		}
		
		return returnMsg;
	}
	
	
	@Override
	public ConfigObject findConfigObj(String configId) throws Exception {
		String hql = "from ConfigObject cfo where cfo.configId = ?";
		Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
		query.setString(0, configId);
		List list = query.list();
		ConfigObject cfobj = new ConfigObject();
		if (list!= null && list.size() > 0) {
			cfobj = (ConfigObject) list.get(0);
		}
		return cfobj;
	}
	
	@Override
	public DataStore findDataStoreById(String dsId) throws Exception {
		String hql = "from DataStore ds where ds.dsId = ?";
		Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
		query.setString(0, dsId);
		List list = query.list();
		DataStore dataStore = new DataStore();
		if (list!= null && list.size() > 0) {
			dataStore = (DataStore) list.get(0);
		}
		return dataStore;
	}
	
	@Override
	public List<Columns> findColumnsById(String dsId) throws Exception {
		String hql = " from Columns cln where cln.dsid = ? ";
		Query query = this.getSessionFactory().getCurrentSession().createQuery(hql);
		query.setString(0, dsId);
		List<Columns> list = query.list();
		return list;
	}
	
	@Override
	public String getMaxPkStr(String sql) throws Exception {
		return this.getPkStr(sql);
	}
	
	@Override
	public boolean saveObject(String sqlText, String[] valuesArr)
			throws Exception {
		return this.executeSqlValues(sqlText,valuesArr);
	}
	
	@Override
	public boolean updateObject(String sqlText, String[] valuesArr,
			String[] whereValue) throws Exception {
		return this.executeUpdateSql(sqlText, valuesArr, whereValue);
	}
	
}
